<script setup lang='ts'>
import { addAgreement, dictList } from '@fl/api/anjutong'
import UpLoadFileOss from '@fl/components/upLoadFile-oss.vue'
import { Editor } from '@fl/origin-components/Editor/index'
import { useRouter } from 'vue-router'

const router = useRouter()
// do not use same name with ref
const form = reactive({
    agreementContent: '',
    agreementType: '',
    agreementTypeName: '',
    agreementUrl: '',
    fileUrl: '',
    source: [],
})
const rules = reactive({
    agreementContent: [
        { trigger: 'blur', validator: customValidator },
    ],
    agreementType: [
        { message: '请选择协议类型', required: true, trigger: 'blur' },
    ],
    agreementUrl: [
        { trigger: 'blur', validator: customValidator },
    ],
    fileUrl: [
        { trigger: 'blur', validator: customValidator },
    ],
    source: [
        { message: '请选择协议来源', required: true, trigger: 'blur' },
    ],
})
const agreementTypeList = ref<any[]>([])
const agreementSourceList = ref<any[]>([])
const ruleFormRef = ref()
const agreementTypeName = computed(() => {
    return agreementTypeList.value.find((item: any) => item.value === form.agreementType)?.label ?? ''
})
const submitLoading = ref(false)
const agreementName = computed(() => {
    try {
        return JSON.parse(form.fileUrl)?.fileName ?? ''
    }
    catch (error) {
        return ''
    }
})
async function getDictData() {
    try {
        const agreementTypeData = await dictList({ dictType: 'agreement_type' })
        agreementTypeList.value = agreementTypeData ?? []
        const agreementSourceData = await dictList({ dictType: 'agreement_source' })
        agreementSourceList.value = agreementSourceData ?? []
    }
    catch (error) {

    }
}
function customValidator(rule, value, callback) {
    console.log(value)
    console.log(rule)
    if (form.agreementContent || form.fileUrl || form.agreementUrl)
        callback()
    else
        callback(new Error('至少填写协议地址、协议内容、协议文档其中一项'))
}
getDictData()
async function onSubmit(formEl: any) {
    if (!formEl)
        return
    await formEl.validate((valid) => {
        if (valid) {
            const save = async () => {
                try {
                    submitLoading.value = true
                    const options = {
                        agreementContent: form.agreementContent,
                        agreementName: agreementName.value,
                        agreementType: form.agreementType,
                        agreementTypeName: agreementTypeName.value,
                        agreementUrl: form.agreementUrl,
                        fileUrl: form.fileUrl,
                        source: form.source?.join(',') ?? '',
                    }
                    await addAgreement(options)
                    submitLoading.value = false
                    router.replace('/content-center/protocol/list')
                }
                catch (error) {
                    submitLoading.value = false
                }
            }
            save()
        }
        else { ElMessage.error('请完善信息') }
    })
}
</script>

<template>
    <div class="p-30 mb-20 bg-white">
        <el-button @click="$router.go(-1)">
            返回列表
        </el-button>

        <el-form ref="ruleFormRef"
                 :model="form"
                 label-width="auto"
                 class="px-30 pb-30 pt-20"
                 label-position="top"
                 :rules="rules"
                 require-asterisk-position="right"
        >
            <el-form-item label="协议类型"
                          prop="agreementType"
            >
                <el-select v-model="form.agreementType"
                           placeholder="请选择协议类型"
                >
                    <el-option v-for="item in agreementTypeList"
                               :key="item.value"
                               :label="item.label"
                               :value="item.value"
                    />
                </el-select>
            </el-form-item>

            <el-form-item label="协议来源"
                          prop="source"
            >
                <el-select v-model="form.source"
                           placeholder="请选择协议来源"
                           clearable
                           multiple
                >
                    <el-option v-for="item in agreementSourceList"
                               :key="item.value"
                               :label="item.label"
                               :value="item.value"
                    />
                </el-select>
            </el-form-item>

            <el-form-item label="协议地址"
                          prop="agreementUrl"
            >
                <el-input v-model="form.agreementUrl"
                          style="width: 240px"
                          placeholder="请输入协议地址"
                />
            </el-form-item>

            <el-form-item label="协议内容"
                          prop="agreementContent"
            >
                <Editor v-model="form.agreementContent"
                        :can-upload-image="false"
                        :can-upload-video="false"
                />
            </el-form-item>

            <el-form-item label="协议文档"
                          prop="fileUrl"
            >
                <UpLoadFileOss v-model="form.fileUrl"
                               :limit="1"
                               @success="submitLoading = false"
                               @beforeupload="submitLoading = true"
                />
            </el-form-item>

            <div class="flex justify-center">
                <el-button type="primary"
                           :loading="submitLoading"
                           @click="onSubmit(ruleFormRef)"
                >
                    保存
                </el-button>

                <el-button @click="$router.go(-1)">
                    取消
                </el-button>
            </div>
        </el-form>
    </div>
</template>
